//
//  AutonymNameController.m
//  NtoccDriverNew
//
//  Created by 张天兴 on 2025/7/7.
//  Copyright © 2025 GCY. All rights reserved.
//

#import "AutonymNameController.h"
#import <WebKit/WebKit.h>
#import "ErrorFaseController.h"
@interface AutonymNameController ()<WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) UIProgressView *progressView;
@end

@implementation AutonymNameController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"人脸识别";
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [WKUserContentController new];
    configuration.allowsInlineMediaPlayback = YES;
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    configuration.preferences = preferences;
    // 注册js方法
    [configuration.userContentController addScriptMessageHandler:self name:@"openNav"];
    [configuration.userContentController addScriptMessageHandler:self name:@"getLoction"];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlStr]];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64) configuration:configuration];
    
    //通过JS 调用到userAgent，然后增加一些内容后赋值
    [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *_Nullable error) {
        NSString *oldUserAgent = result;
        NSString *newUserAgent = [NSString stringWithFormat:@"%@ %@", oldUserAgent, @"ios_webkit"];
        //        NSString *newUserAgent = [NSString stringWithFormat:@"%@%@", oldUserAgent, @";isApp"];
        webView.customUserAgent = newUserAgent;
    }];
    
    [webView addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:nil];
    
    webView.UIDelegate = self;
    webView.navigationDelegate = self;
    webView.allowsBackForwardNavigationGestures = YES;
    [self.view addSubview:webView];
    [webView loadRequest:request];
    self.wkWebView = webView;
    [self.view addSubview:self.progressView];
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    self.navigationItem.leftItemsSupplementBackButton = YES;
    UIImage *bgImage = [[UIImage imageWithColor:UIColor.whiteColor] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0) resizingMode:UIImageResizingModeStretch];
    [DCSpeedy changeNavControllerGradientView:self andBgColor:bgImage andTitleColor:[UIColor blackColor]];
}

- (void)refreshAction:(id)sender {
    [self.wkWebView reload];
}

- (void)backButtonTapClick {
    
    if ([self.wkWebView canGoBack]) {
        [self.wkWebView goBack];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
//    self.title = webView.title;
    NSLog(@"网页标题:%@", webView.title);
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"错误%@", error);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString * absoluteString = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    NSString * scheme = @"https://example.demo.cn";
    // JS调用OC
    if ([absoluteString containsString:scheme]) {
        decisionHandler(WKNavigationActionPolicyAllow);
        [self jsCallOCMethodWithRequest:navigationAction.request];
    }else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

#pragma mark - 拦截scheme并做相应的处理
- (void)jsCallOCMethodWithRequest:(NSURLRequest *)request {
    NSLog(@"URL--%@",request.URL.absoluteString);
    
    NSString * urlString = request.URL.absoluteString;;
//    NSString * scheme = @"/esign/face/return";
    NSString * scheme = @"https://example.demo.cn";
    if ([urlString containsString:scheme]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:NO];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"shimingrenzhengAction" object:nil];
        });
    }
    
}

#pragma mark - H5 向 Native 发送信息
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"js名称:%@", message.name);

}



#pragma mark KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *, id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.wkWebView.estimatedProgress;
        // 加载完成
        if (self.wkWebView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.25f animations:^{
                self.progressView.alpha = 0.0f;
                self.progressView.progress = 0.0f;
            }];
        } else {
            self.progressView.alpha = 1.0f;
        }
    }
}

#pragma mark 进度条
- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 0)];
        _progressView.progressViewStyle = UIProgressViewStyleBar;
        _progressView.tintColor = UIColor.greenColor;
        _progressView.trackTintColor = [UIColor clearColor];
    }
    return _progressView;
}

- (void)dealloc {
    [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end
